package com.bawei.module_mine.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_mine.databinding.ActivityAddressListBinding
import com.bawei.module_mine.intent.AddressIntent
import com.bawei.module_mine.model.entity.AddressEntity
import com.bawei.module_mine.state.AddressState
import com.bawei.module_mine.viewmodel.AddressViewModel
import kotlinx.coroutines.launch

class AddressListActivity : BaseMVIActivity() {
    private lateinit var binding: ActivityAddressListBinding
    private lateinit var viewModel: AddressViewModel
    private lateinit var adapter: AddressAdapter

    private var selectedId: Long? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddressListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 获取跳转传递的当前选中id
        selectedId = intent.getStringExtra("selectedAddressId")?.toLongOrNull()
        generateViewModel()
        initRecyclerView()
        binding.ivBack.setOnClickListener { finish() }
        binding.btnAddAddress.setOnClickListener {
            ARouter.getInstance()
                .build("/module_mine/AddAddressActivity")
                .navigation(this, 1001)
        }
    }

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[AddressViewModel::class.java]
        // 发送获取地址意图
        lifecycleScope.launch {
            viewModel.intents.send(AddressIntent.GetAddressList)
        }
    }

    private fun initRecyclerView() {
        adapter = AddressAdapter(emptyList<AddressEntity>().toMutableList(),
            onEditClick = { address ->
                // 跳转到编辑页面
                val intent = Intent(this, EditAddressActivity::class.java)
                intent.putExtra("addressEntity", address)
                startActivityForResult(intent, 1002)
            },
            onSelectClick = { address ->
                // 选中后返回给订单页
                val intent = Intent()
                intent.putExtra("address", address)
                setResult(RESULT_OK, intent)
                finish()
            }
        )
        adapter.setSelectedId(selectedId)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is AddressState.Init, is AddressState.Loading -> {
                            binding.layoutEmpty.visibility = View.GONE
                            binding.recyclerView.visibility = View.GONE
                        }
                        is AddressState.Success -> {
                            if (state.list.isNullOrEmpty()) {
                                binding.layoutEmpty.visibility = View.VISIBLE
                                binding.recyclerView.visibility = View.GONE
                            } else {
                                binding.layoutEmpty.visibility = View.GONE
                                binding.recyclerView.visibility = View.VISIBLE
                                adapter.updateData(state.list.toMutableList())
                            }
                        }
                        is AddressState.Failed -> {
                            binding.layoutEmpty.visibility = View.VISIBLE
                            binding.recyclerView.visibility = View.GONE
                            Toast.makeText(this@AddressListActivity, state.msg, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }
    }

    override fun getLayoutRootView(): View {
        if (!::binding.isInitialized) {
            binding = ActivityAddressListBinding.inflate(layoutInflater)
        }
        return binding.root
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if ((requestCode == 1001 || requestCode == 1002) && resultCode == RESULT_OK) {
            lifecycleScope.launch {
                viewModel.intents.send(AddressIntent.GetAddressList)
            }
        }
    }
} 